package com.example.demo.service.impl;

import com.example.demo.dto.ApiResponse;
import com.example.demo.dto.UserUpdateRequest;
import com.example.demo.dto.UserInfoDTO;
import com.example.demo.entity.User;
import com.example.demo.entity.UserType;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public User createUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public ApiResponse<?> updateUser(Long id, User user) {
        return userRepository.findById(id)
                .map(existingUser -> {
                    // 更新用户信息
                    if (user.getName() != null) existingUser.setName(user.getName());
                    if (user.getCollege() != null) existingUser.setCollege(user.getCollege());
                    if (user.getPhone() != null) existingUser.setPhone(user.getPhone());
                    if (user.getEmail() != null) existingUser.setEmail(user.getEmail());
                    if (user.getMajor() != null) existingUser.setMajor(user.getMajor());
                    
                    return ApiResponse.success("用户信息更新成功", userRepository.save(existingUser));
                })
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }

    @Override
    public ApiResponse<?> getUserById(Long id) {
        return userRepository.findById(id)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public List<User> getUsersByType(UserType userType) {
        return userRepository.findByUserType(userType);
    }

    @Override
    public List<User> getUsersByCollege(String college) {
        return userRepository.findByCollege(college);
    }

    @Override
    public boolean existsByUsername(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean existsByStudentId(String studentId) {
        return userRepository.existsByStudentId(studentId);
    }

    @Override
    public boolean existsByTeacherId(String teacherId) {
        return userRepository.existsByTeacherId(teacherId);
    }

    @Override
    public ApiResponse<?> getUserByUsername(String username) {
        return userRepository.findByUsername(username)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public Object updateProfile(String username, UserUpdateRequest request) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "用户不存在"));

        if (request.getName() != null) {
            user.setName(request.getName());
        }

        if (request.getOldPassword() != null && request.getNewPassword() != null) {
            if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
                throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "旧密码错误");
            }
            user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        }

        return userRepository.save(user);
    }

    @Override
    public ApiResponse<?> updateAvatar(Long id, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ApiResponse.error("请选择要上传的头像文件");
        }

        return userRepository.findById(id)
                .map(user -> {
                    // TODO: 实现文件上传逻辑
                    String avatarUrl = "avatar_url"; // 这里需要实现实际的文件上传逻辑
                    user.setAvatarUrl(avatarUrl);
                    return ApiResponse.success("头像更新成功", userRepository.save(user));
                })
                .orElse(ApiResponse.error("用户不存在"));
    }

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    @Override
    public UserInfoDTO getUserInfo(String username) {
        User user = findByUsername(username);
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setName(user.getName());
        userInfo.setEmail(user.getEmail());
        userInfo.setPhone(user.getPhone());
        userInfo.setRole(user.getUserType().name());
        userInfo.setDepartment(user.getCollege());
        userInfo.setMajor(user.getMajor());
        userInfo.setStudentId(user.getStudentId());
        userInfo.setTeacherId(user.getTeacherId());
        userInfo.setAvatar(user.getAvatarUrl());
        userInfo.setCollege(user.getCollege());
        return userInfo;
    }
} 